package main

import (
	"encoding/csv"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	// 打开 CSV 文件以写入
	csvFile, err := os.Create("output.csv")
	if err != nil {
		log.Fatalf("Failed to create CSV file: %v", err)
	}
	defer csvFile.Close()

	writer := csv.NewWriter(csvFile)
	defer writer.Flush()

	// 遍历指定目录下的所有文件
	//var names []string
	err = filepath.Walk("/Users/appleli/Downloads/精修", func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			file, err := os.Open(path)
			if err != nil {
				log.Printf("Failed to open file %s: %v", path, err)
				return nil
			}
			defer file.Close()
			//获取文件名带后缀
			filenameWithSuffix := filepath.Base(file.Name())
			fmt.Println("filenameWithSuffix =", filenameWithSuffix)
			//获取文件后缀
			fileSuffix := filepath.Ext(filenameWithSuffix)
			fmt.Println("fileSuffix =", fileSuffix)

			//获取文件名
			filenameOnly := strings.TrimSuffix(filenameWithSuffix, fileSuffix)
			fmt.Println("filenameOnly =", filenameOnly)
			//names=append(names, filenameWithSuffix)
			//数据不这么写，会导致所有数据写在一行上
			err = writer.Write([]string{filenameWithSuffix})
			if err != nil {
				log.Printf("Failed to write record to CSV: %v", err)
			}
		}
		return nil
	})

	/*err = writer.Write(names)
	if err != nil {
		log.Printf("Failed to write record to CSV: %v", err)
	}*/

	fmt.Println("All files have been read and written to output.csv")
}
